package com.jack.thinking.thread.core._3;

import java.util.ArrayList;
import java.util.List;

public class ProducerWithConsumer {
	public static void main(String[] args) {
		List<Integer> list = new ArrayList<>();
		Producer [] pros = new Producer[5];
		Consumer [] cons = new Consumer[5];
		for (int i = 0; i < cons.length; i++) {
			pros[i] = new Producer(list);
			cons[i] = new Consumer(list);
		}
		for (int i = 0; i < cons.length; i++) {
			pros[i].start();
			cons[i].start();
		}
		System.out.println("ending..." + list.size());
	}
}

class Producer extends Thread{
	private List<Integer> list;
	
	public Producer(List<Integer> list) {
		super();
		this.list = list;
	}

	@Override
	public void run() {
		while(true) {
			synchronized (list) {
				while(list.size() == 5) {
					try {
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				System.out.println("produce one");
				list.add(1);
				list.notifyAll();
			}
		}
	}
}

class Consumer extends Thread{
	private List<Integer> list;
	public Consumer(List<Integer> list) {
		super();
		this.list = list;
	}	
	@Override
	public void run() {
		while(true) {
			synchronized (list) {
				while(list.size() == 0) {
					try {
						list.wait();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				list.remove(0);
				System.out.println("consume one");
				list.notifyAll();
			}
		}
	}
}